package com.ruoyi.Apps.Utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TikTokProductUrlParser {

    private static final Pattern TIKTOK_PRODUCT_PATTERN =
            Pattern.compile("(?:https?://)?(?:www\\.)?shop\\.tiktok\\.com/view/product/(\\d+)(?:\\?.*)?");

    /**
     * 从 TikTok 商品链接提取信息
     */
    public static TikTokProductInfo parseProductUrl(String url) {
        if (url == null || url.trim().isEmpty()) {
            return null;
        }

        Matcher matcher = TIKTOK_PRODUCT_PATTERN.matcher(url.trim());
        if (matcher.find()) {
            String productId = matcher.group(1);
            String baseUrl = "https://shop.tiktok.com/view/product/" + productId;

            return new TikTokProductInfo(url, baseUrl, productId);
        }

        return null;
    }

    /**
     * 快速提取为字符串数组 [基础URL, 产品ID]
     */
    public static String[] extractAsArray(String url) {
        TikTokProductInfo info = parseProductUrl(url);
        if (info != null) {
            return new String[]{info.getBaseUrl(), info.getProductId()};
        }
        return null;
    }

    /**
     * 验证是否为有效的 TikTok 商品链接
     */
    public static boolean isValidTikTokProductUrl(String url) {
        return parseProductUrl(url) != null;
    }

    /**
     * 产品信息封装类
     */
    public static class TikTokProductInfo {
        private final String baseUrl;
        private final String productId;

        private final String fullUrl;

        public TikTokProductInfo(String fullUrl, String baseUrl, String productId) {
            this.fullUrl = fullUrl;
            this.baseUrl = baseUrl;
            this.productId = productId;
        }

        public String getBaseUrl() {
            return baseUrl;
        }

        public String getProductId() {
            return productId;
        }

        public String getFullUrl() {
            return fullUrl;
        }

        @Override
        public String toString() {
            return String.format("[%s, %s]", baseUrl, productId);
        }
    }
}